// components/jindu/index.js

Component({
  /**
   * 组件的属性列表
   */
  properties:{
    loadType:{//加载条的类型，line-线形，circle-圆形
      type:String,
      default:'line'
		},
		electricity:{
      type:String,
      default:'0'
		},
		hour:{
      type:String,
      default:'00'
		},
		min:{
      type:String,
      default:'00'
    },
    lineInfo:{
      type:Object,
      default:function(){
        var info={
          colorChange:false,//颜色是否渐变
          loadColor:'#6ee2e1,#2ba98c,#a07e1e'//进度条颜色,渐变时色值至少三种，非渐变时只需一种色值，多传取第一条，多个色值','逗号分开
        }
        return info;
      }
    },
    circleInfo:{
      type:Object,
      default:function(){
        var info={
          foreground:'#FFFFFF',//圆形进度条前景色
          background:'#6ED4BF',//背景色
          circleColor:'#cec4c4'//中心圆盘的颜色
        }
        return info;
      }
    },
    ballInfo:{
      type:Object,
      default:function(){
        var info={
          ballType:'all',//center-只中心出现水波，all-球面也出现水波
          ballSize:100,//球形的大小，最大200，最小50，超出范围可能样式需要再进行优化
          waveColor:'#cec4c4',//水波颜色
          ballPadding:'5px',//球内间距
          
        }
        return info;
      }
    },
    loadText:{//加载时显示的文字
      type:String,
      default:'加载中：'
    },
    loadPercent:{//进度百分比，不需要加%
      type:Number,
      default:0
    }
  },



  /**
   * 组件的初始数据
   */
  data: {
    ballSize_:0

  },
  created(){

  },
  attached(){
    let ballSize_
    if(this.data.ballInfo.ballSize>400){
      ballSize_=400;
    }else if(this.data.ballInfo.ballSize<50){
      ballSize_=50;
    }else{
      ballSize_=this.data.ballInfo.ballSize;
    }
    this.setData({
      ballSize_: ballSize_
    })
  },
  

  /**
   * 组件的方法列表
   */
  methods: {
    init(res) {
      const width = res[0].width
      const height = res[0].height
  
      const canvas = res[0].node
      const ctx = canvas.getContext('2d')
  
      const dpr = wx.getSystemInfoSync().pixelRatio
      canvas.width = width * dpr
      canvas.height = height * dpr
      ctx.scale(dpr, dpr)
  
      const renderLoop = () => {
        this.render(canvas, ctx)
        canvas.requestAnimationFrame(renderLoop)
      }
      canvas.requestAnimationFrame(renderLoop)
  
      const img = canvas.createImage()
      img.onload = () => {
        this._img = img
      }
      img.src = './car.png'
    },
    initCharts:function(){
			// 自动填充数据
			var gaugeOption = this.fillInData();
			var uChartsGauge = null;
      // uChartsGauge = wx.createCanvasContext(gaugeOption.id, this);
      uChartsGauge = wx.createSelectorQuery()
      .select(gaugeOption.id)
      .fields({
        node: true,
        size: true,
      })
      .exec(this.init.bind(this))
      console.log('uChartsGauge',uChartsGauge)
      return
			uChartsGauge.fillStyle = gaugeOption.bgColor;
			uChartsGauge.fillRect(0,0,gaugeOption.width,gaugeOption.width);
			uChartsGauge.save();
			this.drawGauge(gaugeOption,uChartsGauge);
		},
		drawGauge:function(options,ctx){
			var centerPosition = {
				x: options.width / 2,
				y: options.width / 2
			};
			// 总角度数（为什么要加1）假装下图是个圆  0.75PI ~ 0.25PI 实际间隔1.5PI 
					//   1.5PI
					//     ——
			  // 1.0PI	|	   |  0PI
					//     ——
					//   0.5PI
			var totalAngle = options.startAngle - options.endAngle + 1;
			// 计算半径
			var radius = Math.min(centerPosition.x, centerPosition.y);
			
			//画刻度线
			for(let idx = 0,len = options.axisTick.length;idx < len;idx++){
				var gaugeOption = options.axisTick[idx];
				radius -= (gaugeOption.padding + gaugeOption.width / 2);
				var criticalPoint = Math.floor(options.value / (options.max / gaugeOption.number));//大刻度临界点
				var subCriticalPoint = Math.floor(options.value / (options.max / gaugeOption.subNumber / gaugeOption.number));//小刻度临界点
				if(options.value * 1 === 0){
					criticalPoint = -1;//防止0的时候被上颜色
					subCriticalPoint = -1;
				}
				var colors = gaugeOption.color.split(',');
				colors[1] = colors[1] || colors[0];
				var splitAngle = totalAngle / gaugeOption.number;
				var childAngle = totalAngle / gaugeOption.number / gaugeOption.subNumber;
				var startX = -radius - gaugeOption.width * 0.5;
				var endX = -radius - gaugeOption.width * 0.5 + gaugeOption.width;
				var childEndX = -radius - gaugeOption.width * 0.5 + gaugeOption.subWidth;
				
				// 画大刻度
				let maxScaleData = {
					...centerPosition,
					startX,
					endX,
					splitAngle,
					criticalPoint,
					colors,
					startAngle: options.startAngle,
					width: gaugeOption.subHeight,
					number: gaugeOption.number,
				}
				this.drawScale(ctx, maxScaleData);
				
				// 画小刻度
				let minScaleData = {
					...centerPosition,
					startX,
					colors,
					criticalPoint: subCriticalPoint,
					endX: childEndX,
					splitAngle:childAngle,
					startAngle: options.startAngle,
					width: gaugeOption.subHeight,
					number: gaugeOption.number * gaugeOption.subNumber,
				}
				this.drawScale(ctx, minScaleData);
			}
			// 标题
			var titleObj = {
				...options.detail.title,
				...centerPosition,
				name: options.name
			}
			this.drawText(ctx,titleObj);
			
			// 数值
			var _fillText = (options.value * 1) === 0 ? 0 : (options.value * 1).toFixed(1);
			var valueObj = {
				...options.detail.value,
				...centerPosition,
				name: _fillText
			}
			this.drawText(ctx,valueObj);
			
			// 单位
			if(String(options.unit) !== 'false'){
				let unitObj = {
					...options.detail.unit,
					...centerPosition,
					name: options.unit
				}
				var valueLength = (options.value * 1).toFixed(1).length;
				var _oftX = ((valueLength - 1.5) / 2) * valueObj.fontSize;//需要保证单位在数值后面
				unitObj.offsetCenter[0] += _oftX;
				this.drawText(ctx,unitObj);
			}
			
			ctx.draw();
		},
		// 画字
		drawText:function(ctx,data){
			let { fontSize, fontWeight, color, textAlign, offsetCenter, x, y, name } = data;
			// 画标题
			ctx.beginPath();
			// 设置字体
			ctx.font = fontWeight + " " +fontSize + "px MicrosoftYaHei";
			// 设置颜色
			ctx.fillStyle = color;
			// 设置水平对齐方式
			ctx.textAlign = textAlign;
			// 设置中心点
			ctx.translate(x, y);
			// 绘制文字（参数：要写的字，x坐标，y坐标）
			ctx.fillText(name,...offsetCenter);
			ctx.closePath();
			ctx.stroke();
			ctx.restore();
			ctx.save();
		},
		// 画刻度
		drawScale:function(ctx, data){
			let { number, criticalPoint, startX, endX, splitAngle, width, x, y, startAngle,colors } = data;
			// 设置中心点
			ctx.translate(x, y);
			ctx.rotate((startAngle - 1) * Math.PI);
			for (let i = 0; i <= number; i++) {
				ctx.beginPath();
				ctx.setStrokeStyle(i <= criticalPoint ? colors[0] : colors[1]);
				ctx.setLineWidth(width);
				ctx.moveTo(startX, 0);
				ctx.lineTo(endX, 0);
				ctx.stroke();
				ctx.rotate(splitAngle * Math.PI);
			}
			// 清除状态
			ctx.restore();
			ctx.save();
		},
		fillInData:function(){
			var gaugeOption = this.deepClone(mainDefault, this.data.config);
			for(var _k in detailDefault){
				gaugeOption.detail[_k] = this.deepClone(detailDefault[_k], gaugeOption.detail[_k])
			}
			if(gaugeOption.axisTickLength === undefined || gaugeOption.axisTickLength === null){
				if(!(gaugeOption.axisTick instanceof Array)){
					gaugeOption.axisTick = [gaugeOption.axisTick]
				}
			}else{
				gaugeOption.axisTick = gaugeOption.axisTick || [];
			}
			var axisTickLength = gaugeOption.axisTickLength || gaugeOption.axisTick.length || 1;
			var axisTick = [].concat(gaugeOption.axisTick);
			for(var idx = 0,len = axisTickLength;idx < len;idx++){
				var defaultData = idx == 0 ? axisTickDefault : axisTickDefaultSmall;
				axisTick[idx] = axisTick[idx] || {};
				if(idx > 0 && !axisTick[idx].padding){
					axisTick[idx].padding = +axisTick[idx -1].width;
				}
				axisTick[idx] = this.deepClone(defaultData, axisTick[idx]);
			}
			gaugeOption.axisTick = axisTick
			return gaugeOption;
		},
		deepClone:function(source,target){//待优化代码
			var _obj = {};
			source = source || {};
			target = target || {};
			Object.assign(_obj, source, target);
			return JSON.parse(JSON.stringify(_obj));
		}
	
  }
})
